package com.roin.learn.redis.controller;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.roin.learn.redis.entity.User;
import com.roin.learn.redis.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserService userService;

	@RequestMapping("/getById.htm")
	public ModelAndView getById(@RequestParam("id") String userId) {
		ModelAndView mav = new ModelAndView("user/user");
		User user = userService.getById(userId);
		mav.addObject("user", user);
		return mav;
	}
	@RequestMapping("/toAdd.htm")
	public String toAdd( ) {
		return "user/add";
	}
	
	@RequestMapping("/save.do")
	@ResponseBody
	public String save(User user) {
		String userId = userService.save(user);
		if (userId!=null) {
			return "添加成功！";
		}
		return "添加失败！";
	}

	@RequestMapping("/updateById.do")
	@ResponseBody
	public String getUserById(User user) {
		if (user != null) {
			int row = userService.update(user);
			return row > 0 ? "修改成功！" : "修改失败!";
		} else {
			return "修改失败!user参数为空！";
		}
	}
	@RequestMapping("/deleteById.do")
	@ResponseBody
	public String deleteById(@RequestParam(name = "id", required = true)String id) {
		if (userService.deleteById(id)) {
			return "删除成功！";
		}
		return "删除失败！";
	}

	@RequestMapping("/list.htm")
	public String getAllUser(Model model) {
		model.addAttribute("userList", userService.getAll());
		return "user/list";
	}

	@RequestMapping("/page.htm")
	public String getAllUser(Model model, @RequestParam(name = "pageNo", required = true) int pageNo,
			@RequestParam(name = "pageSize", required = true) int pageSize) {
		model.addAttribute("userList", userService.getPage(pageNo, pageSize));
		int count = userService.count();
		int totalPage = count / pageSize + (count % pageSize == 0 ? 0 : 1);
		model.addAttribute("totalPage", totalPage);
		model.addAttribute("pageNo", pageNo);
		return "user/list";
	}
}
